<?php
// +----------------------------------------------------------------------
// | 规格值控制器
// +----------------------------------------------------------------------
// | 2020-4-10
// +----------------------------------------------------------------------
// | Author: 周`
// +----------------------------------------------------------------------

namespace app\admin\controller\mall;

use app\common\controller\AdminController;
use think\App;
use think\facade\Db;
use think\facade\View;

class ItemSpecValue extends AdminController
{
    /**
     * 实例化一个模型实例.
     *
     * @return void
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = app('app\common\model\mall\Item');
        $this->ItemSku = app('app\common\model\mall\ItemSku');
        $this->ItemSkuSpec = app('app\common\model\mall\ItemSkuSpec');
        $this->ItemSpec = app('app\common\model\mall\ItemSpec');
        $this->ItemSpecValue = app('app\common\model\mall\ItemSpecValue');
        $this->ItemCategory = app('app\common\model\common\Categories');
    }

    /**
     * 添加规格
     * @param ArticleRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store()
    {
        $data = $this->request->param();
        try {
            Db::startTrans();


            if ($this->ItemSpecValue->where(['spec_id' => $data['spec_id'], 'spec_value' => $data['spec_value']])->find()) {
                throw new \Exception('规格值已存在');
            }

            $data['app_id'] = $this->model->getApp();
            $specValue = $this->ItemSpecValue->save($data);
            Db::commit();
            return json(['code' => 200, 'msg' => '添加成功', 'data' => ['spec_value_id' => $this->ItemSpecValue->spec_value_id]]);
        } catch (\Exception $exception) {
            Db::rollBack();
            return json(['code' => 1, 'msg' => '添加失败', 'data' => $exception->getMessage()]);
        }
    }

    /**
     * 删除
     * @return \think\response\Json
     * @throws \Exception
     */
    public function destroy()
    {
        $ids = $this->request->param('ids');

        $category = $this->ItemSkuSpec->where('spec_value_id', $ids[0])->find();

        if (!is_array($ids) || empty($ids)) {

            throw new \Exception('请选择删除项');
        }
        Db::startTrans();
        try {
            if ($category) {
                throw new \Exception('该规格下有商品，不能删除');
            }

            $rows = $this->ItemSpecValue->whereIn('spec_value_id', $ids)->select();

            empty($rows) && $this->error('数据不存在');
            $save = $rows->delete();
            DB::commit();
            return json(['code' => 200, 'msg' => '删除成功']);
        } catch (\Exception $exception) {
            DB::rollback();
            return json(['code' => 1, 'msg' => $exception->getMessage()]);
        }
    }


}
